import React, {useState,useRef,useEffect} from 'react';
import {View, Text, FlatList, Button as Button2,  TextInput, TouchableOpacity, StyleSheet,PixelRatio,Alert } from 'react-native';

// import { View, , Button, Alert } from 'react-native';


// import { Container, Header, Content, Footer, FooterTab, Button, Icon, Text } from 'native-base';

import { NativeBaseProvider, Box, Button,Center } from "native-base";

import Video, {VideoRef} from 'react-native-video';
import { request, check, PERMISSIONS, RESULTS } from 'react-native-permissions';

import * as Animatable from 'react-native-animatable';

import { appSchema, tableSchema } from '@nozbe/watermelondb'

import { withObservables } from '@nozbe/watermelondb/react';

import { database } from './index';

import Post from './model/Post';

import {
  Icon,
  List,
  NoticeBar,
  Picker,
  Provider,
  Slider,
  Switch,
  WhiteSpace,
} from '@ant-design/react-native'


// https://github.com/wix/react-native-navigation
// https://github.com/jondot/awesome-react-native
// https://docs.nativebase.io/todo-list
// https://docs.nativebase.io/modal
// https://github.com/jondot/awesome-react-native?tab=readme-ov-file#animation
// https://github.com/jondot/awesome-react-native?tab=readme-ov-file#ui
// https://github.com/TheWidlarzGroup/react-native-video
// https://github.com/Nozbe/WatermelonDB
// https://github.com/oblador/react-native-animatable?tab=readme-ov-file
// react-native-swiper ★6955 - The best Swiper component for React Native
// react-native-splash-screen ★2663 - A splash screen for react-native, hide when application loaded, it works on iOS and Android.

// https://docs.nativebase.io/button


import axios from 'axios';
import { styles} from './MyStyle';
import {MyButton01,showToast} from './UiComponents';


export const Base001 =()=> {
  const [text, setText] = useState('');
  const [puased, setPaused] = useState(false);

  const [posts, setPosts] = useState([]);

  const videoRef = useRef<VideoRef>(null);
  const background = require('./mov_bbb.mp4');

  const handleCreatePost = async () => {
    try {
      // 使用 WatermelonDB 创建一条新记录
      const newPost = await database.write(async () => {
        return await database.get('posts').create(post => {
          post.title = '1 New Post 123'; // 设置 title 字段
          post.body = 'Lorem ipsum dolor sit amet...'; // 设置 body 字段
        });
      });
      fetchPosts();

      // 显示创建成功提示
      // Alert.alert('Success', `Post created with ID: ${newPost.id}`);
    } catch (error) {
      // 捕获并显示错误信息
      console.error('Failed to create post:', error);
      // Alert.alert('Error', 'Failed to create post. Please try again.');
    }
  };


   // 获取所有的 Posts
   const fetchPosts = async () => {
    try {
      const allPosts:Post[] = await database.get('posts').query().fetch(); // 查询所有 Post

      // Alert.alert('Success', `get all: ${allPosts.length}`);
      setPosts(allPosts); // 更新状态
    } catch (error) {
      console.error('Error fetching posts:', error);
    }
  };

  // 删除最后一条记录
  const deleteLastPost = async () => {
    try{
    console.log("deleteLastPost 0");
    const allPosts = await database.get('posts').query().fetch();

    if (allPosts.length === 0) {
      console.log("deleteLastPost 01");
      // Alert.alert('Error', 'No posts to delete');
      return;
    }
    console.log("deleteLastPost 02");

    const lastPost = allPosts[0]; // 获取最后一条记录

     // 使用 writer 包装删除操作
     await database.write(async () => {
      await lastPost.destroyPermanently(); // 删除记录
    });

    // await lastPost.destroyPermanently(); // 删除记录
    // Alert.alert('Success', 'Last post deleted!');
    console.log("deleteLastPost success");
    fetchPosts(); // 重新加载 posts
    console.log("deleteLastPost 1");}
    catch(error){
      console.error('Error deleting post:', error); // 打印错误信息
    }
  };

    // 原始组件
const Post = ({ post }) => (
  <View style={styles.container}>
    <Text style={styles.title}>{post.title}</Text>
    <Text style={styles.body}>{post.body}</Text>
    <Text style={styles.status}>
      {post.isPinned ? 'This post is pinned!' : 'This post is not pinned.'}
    </Text>
  </View>
);

// 增强组件
const enhance = withObservables(['post'], ({ post }) => ({
  post, // 监听 post 的变化
}));

const EnhancedPost = enhance(Post);
  



  const  request1=()=>{
    fetch('https://jsonplaceholder.typicode.com/posts/1')
    .then(response => response.json())
    .then(data => {
      console.log(data)
      Alert.alert('OK', `${JSON.stringify(data)}`);
    })
    .catch(error => console.error('Error:', error));
  }

  const requestCameraPermission = async () => {
    const result = await request(PERMISSIONS.ANDROID.CAMERA); // Android 相机权限
    if (result === RESULTS.GRANTED) {
      Alert.alert('权限已授予', '您可以使用相机！');
    } else {
      Alert.alert('权限被拒绝', '您无法使用相机功能。');
    }
  };

  const handlePress = () => {
    setText('');
    // 点击按钮后，5秒后更新文本
    setTimeout(() => {
      setText('文字已显示3');
    }, 1000); // 5000毫秒 = 5秒
  };






  useEffect(() => {
    fetchPosts(); // 加载数据
  }, []);



  return <View  style={
    { 
      alignItems:'baseline',
      flexDirection: 'column', gap :16,padding: 0,marginBottom :16 }
    }>

{/* <NoticeBar>默认</NoticeBar> */}

<MyButton01 text="Base01" onPress={handlePress}></MyButton01>

<MyButton01 text="ShowToast" onPress={()=>showToast("成功")}></MyButton01>

{/* <Text>Text: {text}</Text>
<Text>Text: {text}</Text>
<Text>Text: {text}</Text> */}



<View style={{flexDirection:"row",alignItems:"center",gap:16}}>


<FlatList
        data={posts}
        keyExtractor={item => item.id}
        renderItem={({ item }) => (
          <EnhancedPost post={item} /> // 为每个 post 渲染增强组件
        )}
      />


{/* npm install -D @babel/plugin-proposal-decorators */}
<MyButton01  text="写入post" onPress={handleCreatePost}/>
<MyButton01 text="读post" onPress={fetchPosts}/>
<MyButton01 text="删除" onPress={deleteLastPost}/>
</View>

{/* 权限开始 */}
<View style={{flexDirection:"row",alignItems:"center",gap:16}}>

<MyButton01  text="fetch网络请求" onPress={request1}/>

<MyButton01  text="动画" onPress={request1}/>

<Animatable.View
        animation={{
          0: { translateX: 0 },  // 初始位置
          0.5: { translateX: 200 },  // 移动 20px
          1: { translateX: 0 },  // 恢复到初始位置
        }}
        direction='reverse'
        iterationCount={10}  // 设置动画无限循环
        duration={4000}
        easing="linear"
        style={styles.box}
      >
        <Text style={styles.text}>Hello, translateX </Text>
      </Animatable.View>



<Animatable.View
        animation="rotate"
        direction='reverse'
        iterationCount={10} 
        duration={4500}
        easing="linear"
        style={styles.box}
      >
        <Text style={styles.text}>Hello, Rotate</Text>
      </Animatable.View>



<MyButton01  text="申请相机权限1" onPress={requestCameraPermission}/>

</View>

{/* 权限结束 */}



<View style={{flexDirection:"row",alignItems:"center",gap:16}}>

<MyButton01  text="Start" onPress={() => setPaused(false)}/>
<MyButton01 text="Pause" onPress={() => setPaused(true)}/>

<Video
    // Can be a URL or a local file.
    source={background}
    // Store reference  
    ref={videoRef}
    paused={puased}
    // Callback when remote video is buffering                                      
    onBuffer={()=>{}}
    // Callback when video cannot be loaded              
    onError={()=>{}}               
    style={styles.backgroundVideo}
    repeat={true}
    controls={false}
    controlsStyles={{
      hidePosition:false,
    }}
   />



</View>

<View style={{flexDirection:"row"}}>


<Text style={styles2.text1}>Text 1</Text>
        <Text style={styles2.text2}>Text 2</Text>
        <Text style={styles2.text3}>Text 3</Text>
        </View>


        <View style={{flexDirection:"row"}}>
        {/* <NativeBaseProvider> */}
          <Center>
        <Button onPress={() => console.log("hello world")}>Click Me</Button>
        <Box alignItems='center'>Hello world10</Box>
        </Center>
     
    {/* </NativeBaseProvider> */}
        </View>



  </View>;
}


const styles2 = StyleSheet.create({
  text1: {
    fontSize: 20,
  },
  text2: {
    fontSize: 30,
  },
  text3: {
    fontSize: 40,
  },
});





